import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import {
  getBanners,
  getHotRecommend,
  getNewAlbum,
  getPlaylistDetail,
  getArtistList
} from '../service/recommend'
export const fetchBannerDataAction = createAsyncThunk(
  'banners',
  async (arg, { dispatch }) => {
    const res = await getBanners()
    dispatch(changeBannersAction(res.banners))
  }
)
export const fetchHotRecommendAction = createAsyncThunk(
  'hotRecommend',
  async (payload: any, { dispatch }) => {
    const res = await getHotRecommend(payload)
    dispatch(changeHotRecommendsAction(res.result))
  }
)
export const fetchNewAlbumAction = createAsyncThunk(
  'newAlbum',
  async (arg, { dispatch }) => {
    const res = await getNewAlbum()
    dispatch(changeNewAlbumsAction(res.albums))
  }
)
const rankingIds = [19723756, 3779629, 2884035]
export const fetchRankingDataAction = createAsyncThunk(
  'rankingData',
  (arg, { dispatch }) => {
    const promises: Promise<any>[] = []
    for (const id of rankingIds) {
      promises.push(getPlaylistDetail(id))
    }
    Promise.all(promises).then((res) => {
      console.log(res) //这里的res是将三个请求的res按顺序放到一个数组中
      /* 这里的filter是为了确定playlist有值 */
      const playlists = res
        .filter((item) => item.playlist)
        .map((item) => item.playlist)
      dispatch(changeRankingsAction(playlists))
    })
  }
)
export const fetchSingerListAction = createAsyncThunk(
  'settleSinger',
  async (arg, { dispatch }) => {
    const res = await getArtistList()
    dispatch(changeArtistListAction(res.artists))
  }
)
interface initialStateType {
  banners: any[]
  hotRecommends: any[]
  newAlbums: any[]
  rankings: any[]
  artistList: any[]
}
const initialState: initialStateType = {
  banners: [],
  hotRecommends: [],
  newAlbums: [],
  rankings: [],
  artistList: []
}
const recommendSlice = createSlice({
  name: 'recommend',
  initialState,

  reducers: {
    changeBannersAction(state, { payload }) {
      state.banners = payload
    },
    changeHotRecommendsAction(state, { payload }) {
      state.hotRecommends = payload
    },
    changeNewAlbumsAction(state, { payload }) {
      state.newAlbums = payload
    },
    changeRankingsAction(state, { payload }) {
      state.rankings = payload
    },
    changeArtistListAction(state, { payload }) {
      state.artistList = payload
    }
  }
})
export const {
  changeBannersAction,
  changeHotRecommendsAction,
  changeNewAlbumsAction,
  changeRankingsAction,
  changeArtistListAction
} = recommendSlice.actions
export default recommendSlice.reducer
